package com.authine.cloudpivot.web.api.secondopen.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.secondopen.domain.AjaxResult;
import com.authine.cloudpivot.web.api.secondopen.domain.IdList;
import com.authine.cloudpivot.web.api.secondopen.domain.Iusi6cgb;
import com.authine.cloudpivot.web.api.secondopen.modules.*;
import com.authine.cloudpivot.web.api.secondopen.service.PurManagementService;
import com.authine.cloudpivot.web.api.secondopen.utils.PageUtil;
import com.authine.cloudpivot.web.api.utils.StringUtils;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购管理控制器
 */
@Api(value = "二开接口",tags = "采购管理控制器")
@RestController
@EnableTransactionManagement
@RequestMapping("/api/PurManagement")
public class PurManagementController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(PurManagementController.class);

    @Autowired(required = true)
    private PurManagementService purManagementService;


    /**
     * 零修/铆焊---采购订单查询PurchaseOrderDTO queryinfos
     *
     */
    @RequestMapping("/queryPurchaseOrder")
    public ResponseResult<Iusi6cgbDeatail> queryPurchaseOrder(@RequestParam(required = false) String supplier,
                                                              @RequestParam(required = false) String starttime,
                                                              @RequestParam(required = false) String endtime,
                                                              @RequestParam(required = false) String sqlx,
                                                              @RequestParam(required = false) Integer pageNum,
                                                              @RequestParam(required = false) Integer pageSize){
        log.info("获取参数:supplier={},starttime={},endtime={},sqlx={}", supplier,starttime,endtime,sqlx);
        List<Iusi6cgb> iusi6cgbs = purManagementService.queryPurchaseOrder(supplier,starttime,endtime,sqlx);
        log.info("查询结果----------iusi6cgbs={}",iusi6cgbs);
        Iusi6cgbDeatail lxwxgcdDeatailVO = new Iusi6cgbDeatail();
        lxwxgcdDeatailVO.setTotal(iusi6cgbs.size());
        if(CollectionUtils.isNotEmpty(iusi6cgbs)){
            lxwxgcdDeatailVO.setIusi6cgbs(PageUtil.startPage(iusi6cgbs,pageNum+1,pageSize));
        }else{
            lxwxgcdDeatailVO.setIusi6cgbs(new ArrayList<>());
        }
        return getOkResponseResult(lxwxgcdDeatailVO, "获取信息成功");
    }


    /**
     * 零修铆焊、零星服务、零星维修工程修改子表状态
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/updatecgbStatus2")
    public void updateStatus(String objId,String processCode,String tableName,String  status){
        log.info("获取参数:objId={},processCode={},tableName={},status", objId, processCode,tableName,status);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)||StringUtils.isBlank(tableName)||StringUtils.isBlank(status)) {
            log.info("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }
        List<Map<String, Object>> bTableSheets=null;
        if ("零修件".equals(tableName)){
            bTableSheets=(List<Map<String, Object>>) bizObject.get("ddxq");
        }else if("零星服务".equals(tableName)){
            bTableSheets=(List<Map<String, Object>>) bizObject.get("lxfwsqcgdddmx");
        }else if("零星维修工程".equals(tableName)){
            bTableSheets=(List<Map<String, Object>>) bizObject.get("lxwxgccgdmx");
        }
        List list=new ArrayList();
        if (!CollectionUtils.isEmpty(bTableSheets)) {
            for (int i = 0; i < bTableSheets.size(); i++) {
                //申请单的id
                String id = String.valueOf(bTableSheets.get(i).get("ycid"));
                list.add(id);
            }
        }
        //修改对应的表单状态
        purManagementService.updatecgbStatus(list,tableName,status);
    }




    /**
     * 修改物资申购单状态
     * @return
     */
    @ApiOperation(value = "修改物资申购单状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idList",value = "ids",required = false,dataType = "char"),
    })
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/updateRequisitionsStatus")
    public AjaxResult updateRequisitionsStatus(String objId,String processCode,String status){
        log.info("获取参数:objId={},processCode={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("参数不完整，直接结束");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }
        //表名
        String tableName = null;
        if ("aspwzcgd".equals(processCode)){
            tableName = "i58av_aspwzsgd";
        }
        if ("wzcgd".equals(processCode)){
            tableName="iusi6_wzsgd";
        }
        Object obj = bizObject.get("xzsgd");
        Map map= JSONObject.parseObject(JSONObject.toJSONBytes(obj), HashMap.class);
        String ids =(String) map.get("id");
        String[] split = ids.split(";");
        IdList idList = new IdList();
        idList.setIds(split);
        idList.setStatus(status);
        purManagementService.updateRequisitionsStatus(idList,tableName);
        return AjaxResult.success("修改成功");
    }

    /**
     * 获取 原材料、产成品、在制品
     */
    @RequestMapping("/getstock")
    @ApiOperation(value = "获取 原材料、产成品、在制品", notes = "获取 原材料、产成品、在制品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryType", value = "类型", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name="queryLot",value = "批量号",dataType = "String",paramType = "query")
    })
    public AjaxResult getStock(@RequestParam String queryType,@RequestParam String queryLot){
        log.info("获取参数：queryType={},queryLot={}",queryType,queryLot);
        if (StringUtils.isBlank(queryType)||StringUtils.isBlank(queryLot)){
            System.out.println("参数不完整");
            return AjaxResult.error("参数不完整");
        }
        List<QADMdmLdWipDetVO> stock = purManagementService.getStock(queryType, queryLot);
        return  AjaxResult.success(stock);
    }

    /**
     * 零修铆焊采购单费用发票回传QAD
     * 一张发票对应一个供应商
     * @param objId
     * @param processCode
     * @return
     */
    @RequestMapping("/lxmhfyfp")
    @ApiOperation(value = "零修铆焊采购单费用发票回传QAD", notes = "零修铆焊采购单费用发票回传QAD")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "objId", value = "业务对象id", dataType = "String", paramType = "query")
    })
    public AjaxResult lxmhfyfp(String objId,String processCode){
        log.info("获取参数:objId={},processCode={},identtify={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("参数不完整，直接结束");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }
        //会计单位
        String kjdw=(String) bizObject.get("kjdw");
        //供应商
        String gys=(String) bizObject.get("gysbm");
        //参考
        String ck=(String) bizObject.get("ck");
        //发票类型
        String fptype=(String) bizObject.get("fplx");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //过账日期
        String gzrq= null;
        if ((Date) bizObject.getDate("gzrq")!=null){
            gzrq=sdf.format((Date) bizObject.getDate("gzrq"));
        }
        //发票日期
        String fprq=null;
        if ((Date) bizObject.getDate("fprq")!=null){
            fprq=sdf.format((Date) bizObject.getDate("fprq"));
        }
        //发票状态代码
        String fpztdm=(String) bizObject.get("fpztdm");
        //发票金额未税
        BigDecimal fpjews=(BigDecimal) bizObject.get("fpjews");
        //发票金额税金
        BigDecimal fpjesj=(BigDecimal) bizObject.get("fpjesj");
        //货币
        String hb=(String) bizObject.get("hb");
        //零件类型
        String ljlx=(String) bizObject.get("sqlx");

        //qad默认值
        String s="SystemDefault";
        QadInvoiceDTO qadInvoiceDTO=new QadInvoiceDTO();
        qadInvoiceDTO.setMdmIcCompnayCode(kjdw);
        qadInvoiceDTO.setMdmIcCreditorCode(gys);
        qadInvoiceDTO.setMdmIcCInvoiceReference(ck);
        //描述
        qadInvoiceDTO.setMdmIcCInvoiceDescription(s);
        qadInvoiceDTO.setMdmIcCInvoiceType(fptype);
        //日记账集代码
        qadInvoiceDTO.setMdmIcCInvoiceDayBookSetCode(s);
        //地点
        qadInvoiceDTO.setMdmIcCInvoiceSiteCode(s);
        //日记账代码
        qadInvoiceDTO.setMdmIcJournalCode(s);
        qadInvoiceDTO.setMdmIdTCInvoicePostingDate(gzrq);
        qadInvoiceDTO.setMdmIdTCInvoiceDate(fprq);
        qadInvoiceDTO.setMdmItCReasonCode(fpztdm);
        qadInvoiceDTO.setMdmIdEtdCInvoiceOriginalTC(fpjews);
        qadInvoiceDTO.setMdmIdEtdCInvoiceTax(fpjesj);
        qadInvoiceDTO.setMdmIcCurrencyCode(hb);
        qadInvoiceDTO.setMdmIlCInvoiceIsTaxable(true);
        qadInvoiceDTO.setMdmIlCInvoiceIsTaxExcluded(true);
        //分账户
        qadInvoiceDTO.setMdmIcDivisionCode(s);
        //成本中心
        qadInvoiceDTO.setMdmIcCostCentreCode(s);
        //项目
        qadInvoiceDTO.setMdmIcProjectCode(s);
        //业务关系代码
        qadInvoiceDTO.setMdmIcShipToBusinessRelation(s);
        //链接到发票
        qadInvoiceDTO.setMdmIiLinkedPeriodYear(0);
        //链接到发票第二个凭证字段
        qadInvoiceDTO.setMdmIcLinkedJournalCode(s);
        //凭证
        qadInvoiceDTO.setMdmIiLinkedCInvoiceVoucher(0);

        //用于设置子表数据并汇总
        //List<LMVO> lmvos=new ArrayList<>();
        List<MdmMFpostinglineVO> mlin=new ArrayList<>();
        //获取子表数据
        List<Map<String, Object>> bTableSheets=(List<Map<String, Object>>) bizObject.get("ddxq");
        BigDecimal je = new BigDecimal(0);
        if (!CollectionUtils.isEmpty(bTableSheets)) {
            for (int i = 0; i < bTableSheets.size(); i++) {
                //id
                String id = String.valueOf(bTableSheets.get(i).get("id"));
                //名称
                String mc = String.valueOf(bTableSheets.get(i).get("wzmc"));
                //账户
                String zh = String.valueOf(bTableSheets.get(i).get("onesub"));
                //分账户
                String fzh = String.valueOf(bTableSheets.get(i).get("twosub"));
                //成本中心
                String cbzx = String.valueOf(bTableSheets.get(i).get("cbzx"));
                //项目
                String xm = String.valueOf(bTableSheets.get(i).get("xm"));
                //金额
                if ("零修件".equals(ljlx)){
                    je = new BigDecimal(String.valueOf(bTableSheets.get(i).get("hjbhs")));
                }
                if ("铆焊件".equals(ljlx)){
                    je = new BigDecimal(String.valueOf(bTableSheets.get(i).get("xjy")));
                }
                MdmMFpostinglineVO mdmMFpostinglineVO = new MdmMFpostinglineVO();
                mdmMFpostinglineVO.setMdmMFPostingLineSequence(i+1);
                mdmMFpostinglineVO.setMdmMFPostingLineText(mc);
                //借方tc
                mdmMFpostinglineVO.setMdmMFPostingLineDebitTC(je);
                //贷方tc
                mdmMFpostinglineVO.setMdmMFPostingLineCreditTC(new BigDecimal(0));
                mdmMFpostinglineVO.setMdmMFcGLCode(zh);
                mdmMFpostinglineVO.setMdmMFcCurrencyCode(hb);
                mdmMFpostinglineVO.setMdmMFcDivisionCode(fzh);
                mdmMFpostinglineVO.setMdmMFcCostCentreCode(cbzx);
                mdmMFpostinglineVO.setMdmMFcProjectCode(xm);

                mlin.add(mdmMFpostinglineVO);

            }
        }
        qadInvoiceDTO.setMdmMFpostingline(mlin);
        QadResultVO sendinvoice = purManagementService.sendinvoice(qadInvoiceDTO);

        String code = sendinvoice.getCode();
        String msg = sendinvoice.getMsg();
        Object data = sendinvoice.getData();
        if ("10000".equals(code)){
            return  AjaxResult.success(msg,data);
        }else{
            return  AjaxResult.error(msg,data);
        }
    }

    /**
     * 零星维修工程采购单查询
     * @param gys
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/querylxwxgc")
    public ResponseResult<LxwxgcdDeatailVO> querylxwxgc(@RequestParam(required = false) String gys,
                                                        @RequestParam(value = "pageNum",required = false) Integer pageNum,
                                                        @RequestParam(value = "pageSize",required = false) Integer pageSize){
        log.info("获取参数：gys={},pageNum={},pageSize={}",gys,pageNum,pageSize);
        List<LxwxgcdVO> querylxwxgc = purManagementService.querylxwxgc(gys);
        LxwxgcdDeatailVO lxwxgcdDeatailVO = new LxwxgcdDeatailVO();
        lxwxgcdDeatailVO.setTotal(querylxwxgc.size());
        if(CollectionUtils.isNotEmpty(querylxwxgc)){
            lxwxgcdDeatailVO.setLxwxgcdVOS(PageUtil.startPage(querylxwxgc,pageNum+1,pageSize));
        }else{
            lxwxgcdDeatailVO.setLxwxgcdVOS(new ArrayList<>());
        }
        return getOkResponseResult(lxwxgcdDeatailVO, "获取信息成功");
    }

    /**
     * 零星维修工程费用发票回传qad
     * @param objId
     * @param processCode
     * @return
     */
    @RequestMapping("/lxwxgcfyfp")
    public AjaxResult lxwxgcfyfp(String objId,String processCode){
        log.info("获取参数:objId={},processCode={},identtify={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("业务对象不存在");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }
        //会计单位
        String kjdw=(String) bizObject.get("kjdw");
        //供应商
        String gys=(String) bizObject.get("gysbm");
        //参考
        String ck=(String) bizObject.get("ck");
        //发票类型
        String fptype=(String) bizObject.get("fplx");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //过账日期
        String gzrq=null;
        if((Date) bizObject.getDate("gzrq")!=null){
            gzrq=sdf.format((Date) bizObject.getDate("gzrq"));
        }
        //发票日期
        String fprq=null;
        if((Date) bizObject.getDate("fprq")!=null){
            fprq=sdf.format((Date) bizObject.getDate("fprq"));
        }
        //发票状态代码
        String fpztdm=(String) bizObject.get("fpztdm");
        //发票金额未税
        BigDecimal fpjews=(BigDecimal) bizObject.get("fpjews");
        //发票金额税金
        BigDecimal fpjesj=(BigDecimal) bizObject.get("fpjesj");
        //货币
        String hb=(String) bizObject.get("hb");
        //qad默认值
        String s="SystemDeafult";
        QadInvoiceDTO qadInvoiceDTO=new QadInvoiceDTO();
        qadInvoiceDTO.setMdmIcCompnayCode(kjdw);
        qadInvoiceDTO.setMdmIcCreditorCode(gys);
        qadInvoiceDTO.setMdmIcCInvoiceReference(ck);
        //描述
        qadInvoiceDTO.setMdmIcCInvoiceDescription(s);
        qadInvoiceDTO.setMdmIcCInvoiceType(fptype);
        //日记账集代码
        qadInvoiceDTO.setMdmIcCInvoiceDayBookSetCode(s);
        //地点
        qadInvoiceDTO.setMdmIcCInvoiceSiteCode(s);
        //日记账代码
        qadInvoiceDTO.setMdmIcJournalCode(s);
        qadInvoiceDTO.setMdmIdTCInvoicePostingDate(gzrq);
        qadInvoiceDTO.setMdmIdTCInvoiceDate(fprq);
        qadInvoiceDTO.setMdmItCReasonCode(fpztdm);
        qadInvoiceDTO.setMdmIdEtdCInvoiceOriginalTC(fpjews);
        qadInvoiceDTO.setMdmIdEtdCInvoiceTax(fpjesj);
        qadInvoiceDTO.setMdmIcCurrencyCode(hb);
        qadInvoiceDTO.setMdmIlCInvoiceIsTaxable(true);
        qadInvoiceDTO.setMdmIlCInvoiceIsTaxExcluded(true);
        //分账户
        qadInvoiceDTO.setMdmIcDivisionCode(s);
        //成本中心
        qadInvoiceDTO.setMdmIcCostCentreCode(s);
        //项目
        qadInvoiceDTO.setMdmIcProjectCode(s);
        //业务关系代码
        qadInvoiceDTO.setMdmIcShipToBusinessRelation(s);
        //链接到发票
        qadInvoiceDTO.setMdmIiLinkedPeriodYear(0);
        //链接到发票第二个凭证字段
        qadInvoiceDTO.setMdmIcLinkedJournalCode(s);
        //凭证
        qadInvoiceDTO.setMdmIiLinkedCInvoiceVoucher(0);
        List<MdmMFpostinglineVO> mlin=new ArrayList<>();
        List<Map<String, Object>> bTableSheets=(List<Map<String, Object>>) bizObject.get("lxwxgccgdmx");
        System.out.println(1);
        if (!CollectionUtils.isEmpty(bTableSheets)) {
            for (int i = 0; i < bTableSheets.size(); i++) {
                //id
                String id = String.valueOf(bTableSheets.get(i).get("id"));
                //明细行描述
                String mxhms = String.valueOf(bTableSheets.get(i).get("dh"));
                //借方TC金额
                BigDecimal jftcje=new BigDecimal(String.valueOf(bTableSheets.get(i).get("sjje")));
                //总账户
                String zzh = String.valueOf(bTableSheets.get(i).get("zzh"));
                //分账户
                String fzh = String.valueOf(bTableSheets.get(i).get("fzh"));
                //成本中心
                String cbzx = String.valueOf(bTableSheets.get(i).get("cbzx"));
                //项目
                //String xm = String.valueOf(bTableSheets.get(i).get("xm"));
                MdmMFpostinglineVO mdmMFpostinglineVO = new MdmMFpostinglineVO();
                mdmMFpostinglineVO.setMdmMFPostingLineSequence(i+1);
                mdmMFpostinglineVO.setMdmMFPostingLineText(mxhms);
                mdmMFpostinglineVO.setMdmMFPostingLineDebitTC(jftcje);
                mdmMFpostinglineVO.setMdmMFPostingLineCreditTC(new BigDecimal(0));
                mdmMFpostinglineVO.setMdmMFcGLCode(zzh);
                mdmMFpostinglineVO.setMdmMFcCurrencyCode(hb);
                mdmMFpostinglineVO.setMdmMFcDivisionCode(fzh);
                mdmMFpostinglineVO.setMdmMFcCostCentreCode(cbzx);
                mlin.add(mdmMFpostinglineVO);
            }
        }
        qadInvoiceDTO.setMdmMFpostingline(mlin);
        QadResultVO sendinvoice = purManagementService.sendinvoice(qadInvoiceDTO);
        String code = sendinvoice.getCode();
        String msg=sendinvoice.getMsg();
        Object data = sendinvoice.getData();
        if ("10000".equals(code)){
            return AjaxResult.success(msg,data);
        }else {
            return AjaxResult.error(msg,data);
        }
    }

    /**
     * 零星服务采购单费用发票回传qad
     * @param objId
     * @param processCode
     * @return
     */
    @RequestMapping("/lxfwfyfp")
    public AjaxResult lxfwfyfp(String objId,String processCode){
        log.info("获取参数:objId={},processCode={},identtify={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("业务对象不存在");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }
        //会计单位
        String kjdw=(String) bizObject.get("kjdw");
        //供应商
        String gys=(String) bizObject.get("gysbm");
        //参考
        String ck=(String) bizObject.get("ck");
        //发票类型
        String fptype=(String) bizObject.get("fplx");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //过账日期
        String gzrq=null;
        if((Date) bizObject.getDate("gzrq")!=null){
            gzrq=sdf.format((Date) bizObject.getDate("gzrq"));
        }
        //发票日期
        String fprq=null;
        if((Date) bizObject.getDate("fprq")!=null){
            fprq=sdf.format((Date) bizObject.getDate("fprq"));
        }
        //发票状态代码
        String fpztdm=(String) bizObject.get("fpztdm");
        //发票金额未税
        BigDecimal fpjews=(BigDecimal) bizObject.get("fpjews");
        //发票金额税金
        BigDecimal fpjesj=(BigDecimal) bizObject.get("fpjesj");
        //货币
        String hb=(String) bizObject.get("hb");
        //qad默认值
        String s="SystemDeafult";
        QadInvoiceDTO qadInvoiceDTO=new QadInvoiceDTO();
        qadInvoiceDTO.setMdmIcCompnayCode(kjdw);
        qadInvoiceDTO.setMdmIcCreditorCode(gys);
        qadInvoiceDTO.setMdmIcCInvoiceReference(ck);
        //描述
        qadInvoiceDTO.setMdmIcCInvoiceDescription(s);
        qadInvoiceDTO.setMdmIcCInvoiceType(fptype);
        //日记账集代码
        qadInvoiceDTO.setMdmIcCInvoiceDayBookSetCode(s);
        //地点
        qadInvoiceDTO.setMdmIcCInvoiceSiteCode(s);
        //日记账代码
        qadInvoiceDTO.setMdmIcJournalCode(s);
        qadInvoiceDTO.setMdmIdTCInvoicePostingDate(gzrq);
        qadInvoiceDTO.setMdmIdTCInvoiceDate(fprq);
        qadInvoiceDTO.setMdmItCReasonCode(fpztdm);
        qadInvoiceDTO.setMdmIdEtdCInvoiceOriginalTC(fpjews);
        qadInvoiceDTO.setMdmIdEtdCInvoiceTax(fpjesj);
        qadInvoiceDTO.setMdmIcCurrencyCode(hb);
        qadInvoiceDTO.setMdmIlCInvoiceIsTaxable(true);
        qadInvoiceDTO.setMdmIlCInvoiceIsTaxExcluded(true);
        //分账户
        qadInvoiceDTO.setMdmIcDivisionCode(s);
        //成本中心
        qadInvoiceDTO.setMdmIcCostCentreCode(s);
        //项目
        qadInvoiceDTO.setMdmIcProjectCode(s);
        //业务关系代码
        qadInvoiceDTO.setMdmIcShipToBusinessRelation(s);
        //链接到发票
        qadInvoiceDTO.setMdmIiLinkedPeriodYear(0);
        //链接到发票第二个凭证字段
        qadInvoiceDTO.setMdmIcLinkedJournalCode(s);
        //凭证
        qadInvoiceDTO.setMdmIiLinkedCInvoiceVoucher(0);
        List<MdmMFpostinglineVO> mlin=new ArrayList<>();
        List<Map<String, Object>> bTableSheets=(List<Map<String, Object>>) bizObject.get("lxfwsqcgdddmx");
        if (!CollectionUtils.isEmpty(bTableSheets)) {
            for (int i = 0; i < bTableSheets.size(); i++) {
                //id
                String id = String.valueOf(bTableSheets.get(i).get("id"));
                //明细行描述
                String mxhms = String.valueOf(bTableSheets.get(i).get("dh"));
                //借方TC金额
                BigDecimal jftcje=new BigDecimal(String.valueOf(bTableSheets.get(i).get("fwfy")));
                //总账户
                String zzh = String.valueOf(bTableSheets.get(i).get("zzh"));
                //分账户
                String fzh = String.valueOf(bTableSheets.get(i).get("fzh"));
                //成本中心
                String cbzx = String.valueOf(bTableSheets.get(i).get("cbzx"));
                //项目
                //String xm = String.valueOf(bTableSheets.get(i).get("xm"));
                MdmMFpostinglineVO mdmMFpostinglineVO = new MdmMFpostinglineVO();
                mdmMFpostinglineVO.setMdmMFPostingLineSequence(i+1);
                mdmMFpostinglineVO.setMdmMFPostingLineText(mxhms);
                mdmMFpostinglineVO.setMdmMFPostingLineDebitTC(jftcje);
                mdmMFpostinglineVO.setMdmMFPostingLineCreditTC(new BigDecimal(0));
                mdmMFpostinglineVO.setMdmMFcGLCode(zzh);
                mdmMFpostinglineVO.setMdmMFcCurrencyCode(hb);
                mdmMFpostinglineVO.setMdmMFcDivisionCode(fzh);
                mdmMFpostinglineVO.setMdmMFcCostCentreCode(cbzx);
                mlin.add(mdmMFpostinglineVO);
            }
        }
        qadInvoiceDTO.setMdmMFpostingline(mlin);
        QadResultVO sendinvoice = purManagementService.sendinvoice(qadInvoiceDTO);
        String code = sendinvoice.getCode();
        String msg=sendinvoice.getMsg();
        Object data = sendinvoice.getData();
        if ("10000".equals(code)){
            return AjaxResult.success(msg,data);
        }else {
            return AjaxResult.error(msg,data);
        }
    }

    /**
     * 零星服务申请采购单查询
     * @param gys
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/querylxfwsq")
    public ResponseResult<LxfwdDeatailVo> querylxfwsq(@RequestParam(required = false) String gys,
                                                      @RequestParam(value = "pageNum",required = false) Integer pageNum,
                                                      @RequestParam(value = "pageSize",required = false) Integer pageSize){
        log.info("获取参数：gys={}",gys);
        List<LxfwdVo> lxfwdVos=purManagementService.querylxfwsq(gys);
        LxfwdDeatailVo lxfwdDeatailVo = new LxfwdDeatailVo();
        lxfwdDeatailVo.setTotal(lxfwdVos.size());
        if(CollectionUtils.isNotEmpty(lxfwdVos)){
            lxfwdDeatailVo.setLxfwdVos(PageUtil.startPage(lxfwdVos,pageNum+1,pageSize));
        }else{
            lxfwdDeatailVo.setLxfwdVos(new ArrayList<>());
        }
        return getOkResponseResult(lxfwdDeatailVo, "获取信息成功");

    }


    /**
     * 零修铆焊费用订单回传qad
     * @param objId
     * @param processCode
     * @return
     */
    @RequestMapping("/lxmdcgdhc")
    public AjaxResult lxmhcgdLimit(String objId,String processCode){
        log.info("获取参数:objId={},processCode={},identtify={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("业务对象不存在");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }
        //订单号
        String ddh=(String) bizObject.get("ddh");
        //供应商
        String gys=(String) bizObject.get("gysbm");
        //发货至
        String fhz=(String) bizObject.get("fhz");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //订单日期
        String ddrq= null;
        if ((Date) bizObject.getDate("ddrq")!=null){
            ddrq=sdf.format((Date) bizObject.get("ddrq"));
        }
        //截止日期
        String jzrq=null;
        if ((Date) bizObject.get("jzrq")!=null){
            jzrq=sdf.format((Date) bizObject.get("jzrq"));
        }
        //票据开往
        String pjkw=(String) bizObject.get("pjkw");
        //折扣表
        String zkb=(String) bizObject.get("gysbm");
        //申请类型
        String sqlx=(String) bizObject.get("sqlx");
        QADExpenseOrderVO qadExpenseOrderVO = new QADExpenseOrderVO();
        qadExpenseOrderVO.setMdmPoNbr(ddh);
        qadExpenseOrderVO.setMdmPoVend(gys);
        qadExpenseOrderVO.setMdmPoShip(fhz);
        qadExpenseOrderVO.setMdmPoOrdDate(ddrq);
        qadExpenseOrderVO.setMdmPoDueDate(jzrq);
        qadExpenseOrderVO.setMdmPoBill(pjkw);
        qadExpenseOrderVO.setMdmPoPrList2(zkb);

        //用于设置子表数据并汇总
        List<LMVO> lmvos=new ArrayList<>();
        //获取子表数据
        List<Map<String, Object>> bTableSheets=(List<Map<String, Object>>) bizObject.get("ddxq");
        Double je=new Double(0);
        if (!CollectionUtils.isEmpty(bTableSheets)) {
            for (int i = 0; i < bTableSheets.size(); i++) {
                //id
                String id=String.valueOf(bTableSheets.get(i).get("id"));
                //名称
                String mc=String.valueOf(bTableSheets.get(i).get("wzmc"));
                //账户
                String zh=String.valueOf(bTableSheets.get(i).get("onesub"));
                //分账户
                String fzh=String.valueOf(bTableSheets.get(i).get("twosub"));
                //成本中心
                String cbzx=String.valueOf(bTableSheets.get(i).get("cbzx"));
                //项目
                String xm=String.valueOf(bTableSheets.get(i).get("xm"));
                //金额
                if("零修件".equals(sqlx)){
                    je=Double.parseDouble(String.valueOf(bTableSheets.get(i).get("hjbhs")));
                }
                if("铆焊件".equals(sqlx)){
                    je=Double.parseDouble(String.valueOf(bTableSheets.get(i).get("xjy")));
                }
                LMVO lmvo = new LMVO();
                lmvo.setId(id);
                lmvo.setMc(mc);
                lmvo.setZh(zh);
                lmvo.setFzh(fzh);
                lmvo.setCbzx(cbzx);
                lmvo.setXm(xm);
                lmvo.setJe(je);
                lmvos.add(lmvo);
            }
        }
        //数据汇总方法,获取汇总后的订单
        //qad子表传输列表对象
        List<QADMdmPodDetVO> mdmPodDet = new ArrayList<>();
        //根据条件汇总子表
        List<LMVO> lmvos1 = DdDataSummary(lmvos);
        for (int i = 0; i <lmvos1.size() ; i++) {
            LMVO lmvo = lmvos1.get(i);
            String mc = lmvo.getMc();
            String newmc=null;
            //零件号截取18位补=
            if (mc.length()>18){
                newmc=mc.substring(0,18)+"=";
            }else {
                newmc=mc;
            }
            //qad子表传输对象
            QADMdmPodDetVO qadMdmPodDetVO = new QADMdmPodDetVO();
            qadMdmPodDetVO.setMdmPodetLine(i+1);
            qadMdmPodDetVO.setMdmPodetPart(newmc);
            //数量固定为1
            qadMdmPodDetVO.setMdmPodetQtyOrd(1);
            //单位固定为批
            qadMdmPodDetVO.setMdmPodetUm("批");
            //单位成本
            qadMdmPodDetVO.setMdmPodetPurCost(lmvo.getJe());
            //主账户
            qadMdmPodDetVO.setMdmPodetAcct(lmvo.getZh());
            //分账户
            qadMdmPodDetVO.setMdmPodetSub(lmvo.getFzh());
            //成本中心
            qadMdmPodDetVO.setMdmPodetCc(lmvo.getCbzx());
            //项目
            qadMdmPodDetVO.setMdmPodetProj(lmvo.getXm());
            mdmPodDet.add(qadMdmPodDetVO);
        }
        qadExpenseOrderVO.setMdmPodDet(mdmPodDet);

        QadResultVO qadResultVO = purManagementService.sendPopoMt2(qadExpenseOrderVO);
        log.info("qad返回信息：qadresultvo={}",qadResultVO);
        String code = qadResultVO.getCode();
        String msg = qadResultVO.getMsg();
        Object data = qadResultVO.getData();
        if ("10000".equals(code)){
            return AjaxResult.success(msg,data);
        }else{
            return AjaxResult.error(msg,data);
        }
    }
    /**
     * 费用订单数据处理
     */
    public List<LMVO> DdDataSummary(List<LMVO> lm){
        List<LMVO> ll=new ArrayList<>();
        //根据供应商、账户、分账户、成本中心进行分组
        lm.parallelStream().collect(Collectors.groupingBy(d ->d.getZh()+d.getFzh() +d.getCbzx(),Collectors.toList()))
                .forEach((id,groupList)->{
                    groupList.stream().reduce(
                            (a,b)-> new LMVO(a.getMc(),
                                    a.getCbzx(),
                                    a.getZh(),
                                    a.getFzh(),
                                    a.getJe(),
                                    b.getJe()))
                            .ifPresent(ll::add);
                });
        return ll;
    }

    /**
     * 报废通知单回传QAD
     * @param objId
     * @param processCode
     * @return
     */
    @RequestMapping("/bftzdhc")
    @ApiOperation(value = "报废通知单回传QAD",notes = "报废通知单回传QAD")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "objId", value = "业务对象id", dataType = "String", paramType = "query")
    })
    public AjaxResult bftzdLimit(String objId,String processCode) {
        log.info("获取参数:objId={},processCode={},identtify={}", objId, processCode);
        if (StringUtils.isBlank(objId) || StringUtils.isBlank(processCode)) {
            log.info("参数不完整，直接结束");
            return AjaxResult.error("参数不完整，直接结束");
        }
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        //获取业务数据
        BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject(processCode, objId);
        if (bizObject == null) {
            log.info("业务对象不存在");
            return AjaxResult.error("参数不完整，直接结束");
        }
        String wId = bizObject.getWorkflowInstanceId();
        log.info("TargetOwner:wId={}", wId);
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(wId);
        if (wiModel == null) {
            log.info("业务流程对象不存在");
        }
        //类型（原材料、在制品、产成品)
        String  lx =(String) bizObject.get("lx");
        //领料单
        String  lld =(String) bizObject.get("lld");
        String reason=null;
        if("原材料".equals(lx)){
            reason=(String) bizObject.get("ckyyycl");
        }
        if("在制品".equals(lx)){
            //出库原因（库存-在制品)
            reason=(String) bizObject.get("yydm");
        }
        if("产成品".equals(lx)){
            //出库原因（库存-在制品)
            reason=(String) bizObject.get("kcyy");
        }
        //部门
        String bm=(String) bizObject.get("cbzx");
        //账户
        //分账户
        //成本中心
        //项目
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //日期
        String rq= null;
        if ((Date) bizObject.getDate("rq")!=null){
            rq= sdf.format((Date) bizObject.getDate("rq")) ;
        }
        //需求日期
        String xqrq=null;
        if ((Date) bizObject.getDate("xqrq")!=null){
            xqrq=sdf.format((Date) bizObject.getDate("xqrq"));
        }

        //地点
        String dd=(String) bizObject.get("dd");
        //备注
        String bz=(String) bizObject.get("bz");
        //人员编号
        SelectionValue creater = bizObject.getCreater();
        String id = creater.getId();
        String jobbnumber = purManagementService.getJobNumberById(id);
        //获取mes号
        String mesnumber = purManagementService.getMesByJobNumber(jobbnumber);

        //qad报废单传输对象
        QADScrapOrderDTO dto = new QADScrapOrderDTO();
        dto.setMdmScrapOrderType(lx);
        dto.setMdmScrapOrderNbr(lld);
        //原因
        dto.setMdmScrapOrderReason(reason);
        dto.setMdmScrapOrderDept(bm);
        dto.setMdmScrapOrderVarAcct("");
        dto.setMdmScrapOrderVarSub("");
        dto.setMdmScrapOrderVarCc("");
        dto.setMdmScrapOrderProject("");
        dto.setMdmScrapOrderDate(rq);
        dto.setMdmScrapOrderReqDate(xqrq);
        dto.setMdmScrapOrderSite(dd);

                dto.setMdmScrapOrderRmks(bz);
        dto.setMdmScrapOrderuser(mesnumber);
        List<MdmLdDetDTO> mdmLdDetDTOList=new ArrayList<>();
        List<Map<String, Object>> bTableSheets=(List<Map<String, Object>>) bizObject.get("sqmxb");
        if (!CollectionUtils.isEmpty(bTableSheets)){
            for (int i = 0; i < bTableSheets.size(); i++) {
                //零件号
                String  ljh=String.valueOf(bTableSheets.get(i).get("cpbm"));
                //地点
                String zbdd=String.valueOf(bTableSheets.get(i).get("dd"));
                //库位
                String kw=String.valueOf(bTableSheets.get(i).get("kw"));
                //货格
                String hg=String.valueOf(bTableSheets.get(i).get("hg"));
                //批次
                String pc=String.valueOf(bTableSheets.get(i).get("pc"));
                //参考
                String ck=String.valueOf(bTableSheets.get(i).get("ckh"));
                //需求量 Deimel
                MdmLdDetDTO mdmLdDetDTO = new MdmLdDetDTO();
                mdmLdDetDTO.setMdmLdlinePart(ljh);
                mdmLdDetDTO.setMdmLdlineSite(zbdd);
                mdmLdDetDTO.setMdmLdlineLoc(kw);
                mdmLdDetDTO.setMdmLdlineGrid(hg);
                mdmLdDetDTO.setMdmLdlineLot(pc);
                mdmLdDetDTO.setMdmLdlineRef(ck);
                mdmLdDetDTOList.add(mdmLdDetDTO);
            }
        }
        dto.setMdmLdDet(mdmLdDetDTOList);
        log.info("获取参数：dto={}", JSON.toJSON(dto));
        QadResultVO qadResultVO = purManagementService.sendScrap(dto);
        String code = qadResultVO.getCode();
        String msg = qadResultVO.getMsg();
        Object data = qadResultVO.getData();
        if ("10000".equals(code)){
            return AjaxResult.success(msg,data);
        }else {
            return AjaxResult.error(msg);
        }
    }
    /**
     * 获取计划外出库原因（库存）分页
     */
//    @RequestMapping("/getOutPlanRsn")
//    public ResponseResult<OutPlanRsnDeatailVO> getOutPlanRsn(@RequestParam(value = "pageNum",required = false) Integer pageNum,
//                                    @RequestParam(value = "pageSize",required = false) Integer pageSize){
//        List<OutPlanRsnVO> outPlanRsnVOS = purManagementService.getOutPlanRsn();
//        OutPlanRsnDeatailVO outPlanRsnDeatailVO = new OutPlanRsnDeatailVO();
//        outPlanRsnDeatailVO.setTotal(outPlanRsnVOS.size());
//        if(CollectionUtils.isNotEmpty(outPlanRsnVOS)){
//            outPlanRsnDeatailVO.setOutPlanRsnVOS(PageUtil.startPage(outPlanRsnVOS,pageNum+1,pageSize));
//        }else{
//            outPlanRsnDeatailVO.setOutPlanRsnVOS(new ArrayList<>());
//        }
//        return getOkResponseResult(outPlanRsnDeatailVO,"获取信息成功");
//    }
    /**
     * 获取计划外出库原因（库存）
     */
    @RequestMapping("/getOutPlanRsn")
    public AjaxResult getOutPlanRsn(){
        List<ScrapVO> outPlanRsn = purManagementService.getOutPlanRsn();
        if (CollectionUtils.isNotEmpty(outPlanRsn)){
            return AjaxResult.success(outPlanRsn);
        }else {
            return AjaxResult.error("获取参数为空");
        }
    }

    /**
     * 获取计划外出库原因(在制品)
     */
    @RequestMapping("/getScrapCode")
    @ApiOperation(value = "获取计划外出库原因(在制品)",notes = "获取计划外出库原因(在制品)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "desc", value = "原因描述", dataType = "String", paramType = "query")
    })
    public ResponseResult<ScrapDeatailVO> getScrapCode(@RequestParam(required = false) String desc,
                                                       @RequestParam(required = false) Integer pageNum,
                                                       @RequestParam(required = false) Integer pageSize ){
       List<ScrapVO> scrapVOS=purManagementService.getScrapCode(desc);
        ScrapDeatailVO scrapDeatailVO = new ScrapDeatailVO();
        scrapDeatailVO.setTotal(scrapVOS.size());
        if(CollectionUtils.isNotEmpty(scrapVOS)){
            scrapDeatailVO.setScrapVO(PageUtil.startPage(scrapVOS,pageNum+1,pageSize));
        }else{
            scrapDeatailVO.setScrapVO(new ArrayList<>());
        }
        return getOkResponseResult(scrapDeatailVO, "获取信息成功");
    }
}
